package com.qianjiangcloud.store.activity.account;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.NumberPicker;
import android.widget.TextView;

import com.qianjiangcloud.store.BaseDoFragment;
import com.qianjiangcloud.store.Run;
import com.qianjiangcloud.store.activity.AgentActivity;
import com.qianjiangcloud.store.http.JsonRequestBean;
import com.qianjiangcloud.store.http.JsonTask;
import com.qianjiangcloud.store.http.JsonTaskHandler;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshBase;
import com.qianjiangcloud.store.ui.pulltorefresh.lib.PullToRefreshListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import com.qianjiangcloud.store.R;

public class AccountBalanceNewFragment extends BaseDoFragment {
    public static final String ALLBILL = "";
    public static final String INBILL = "in";
    public static final String OUTBILL = "out";
    public static final String NOFINISHBILL = "act";
    public static final String FINISHBILL = "fin";
    public static final String TIXIAN = "tx";
    public static final String RECHARGE = "cz";
    private static final int CHARGE_REQUEST_CODE = 0x1001;
    private List<JSONObject> accountLists = new ArrayList<JSONObject>();
    public final int CHARGECARD_REQUEST_CODE = 0x1000;
    private PullToRefreshListView mListView;
    private MyBillAdapter mAdapter;
    private String pay_status = "";
    private List<BillPayInfo> payInfos = new ArrayList<BillPayInfo>();
    private int mPageNum;
    private JsonTask mTask;
    private boolean isFrist = true;
    private int pageNo=0;
    private int pageSize=10;
    private  int total=0;
    private int currentTotal=0;

    public AccountBalanceNewFragment() {
        super();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActionBar.setShowTitleBar(false);
        mActionBar.setShowHomeView(false);
    }

    @Override
    public void init(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_account_balance_new, null);
        mListView = (PullToRefreshListView) findViewById(R.id.listview);
        findViewById(R.id.account_balance_money).setOnClickListener(this);
        findViewById(R.id.account_balance_online_charge).setOnClickListener(this);
//		findViewById(R.id.account_balance_withdraw).setOnClickListener(this);
        findViewById(R.id.fragment_balance_cancel).setOnClickListener(this);
//        Run.excuteJsonTask(new JsonTask(), new LoadCheckoutHistoryTask(0));
//        Run.excuteJsonTask(new JsonTask(), new GetAcountInfoTask());
        findViewById(R.id.title1).setOnClickListener(this);
        mAdapter = new MyBillAdapter();
        mListView.setPullToRefreshEnabled(true);
        mListView.setRefreshing(true);
        mListView.getRefreshableView().setAdapter(mAdapter);


        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if (scrollState== NumberPicker.OnScrollListener.SCROLL_STATE_IDLE)
                {
                    if (currentTotal<total)
                    {
                        loadNextPage();
                    }
                }

            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem,
                                 int visibleItemCount, int totalItemCount) {


            }
        });

        mListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener() {

            @Override
            public void onRefresh() {
                loadRefreshPage();
            }
            @Override
            public void onRefreshMore() {
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        Log.e("Raymond Test", "onResume()");
        Run.excuteJsonTask(new JsonTask(), new LoadCheckoutHistoryTask(0));
        loadRefreshPage();
    }


    //下拉刷新
    private void loadRefreshPage() {
//        payInfos.clear();
        if (mTask != null && mTask.isExcuting)
            return;
        pageNo = 1;
        total=0;
        currentTotal=0;
        if(payInfos != null){
            payInfos.clear();
        }
        mTask = new JsonTask();
        Run.excuteJsonTask(mTask, new MyAccountDetailTask());
        mAdapter.notifyDataSetChanged();
    }




	private void loadNextPage() {
		this.pageNo = pageNo + 1;
		if (this.pageNo == 1) {
			payInfos.clear();
			mAdapter.notifyDataSetChanged();
		} else {
			isFrist=false;
			if (mTask != null && mTask.isExcuting)
				return;
		}
		mTask = new JsonTask();
		Run.excuteJsonTask(mTask, new MyAccountDetailTask());
	}
    @Override
    public void onCheckoutHistoryLoaded(String json_str) {
        hideLoadingDialog_mt();
        try {
            JSONObject all = new JSONObject(json_str);
            if (Run.checkRequestJson(mActivity, all)) {
                JSONObject data = all.optJSONObject("data");
                String balance = data.optString("total");
                Double d = Double.parseDouble(balance);
                DecimalFormat df = new DecimalFormat("0.00");
                ((TextView) findViewById(R.id.account_balance_money))
                        .setText(df.format(d));
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.account_balance_charge) {//跳转到充值卡充值界面
            startActivityForResult(AgentActivity.intentForFragment(mActivity,
                    AgentActivity.FRAGMENT_BALANCE_CHARGE), CHARGECARD_REQUEST_CODE);
        } else if (id == R.id.account_balance_online_charge) {//跳转到预存款充值（微信和支付宝充值）
            startActivityForResult(AgentActivity.intentForFragment(mActivity,
                    AgentActivity.FRAGMENT_CAHARGE_METHODS), CHARGE_REQUEST_CODE);
        } else if (id == R.id.account_balance_withdraw) {

        } /*else if (id == R.id.title1) {//跳转到收入详情界面
            startActivity(AgentActivity.intentForFragment(mActivity,
                    AgentActivity.FRAGMENT_ACCOUNT_EARNING));
        }*/ else if (id == R.id.fragment_balance_cancel) {
            mActivity.finish();
        } else {
            super.onClick(v);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if ((requestCode == CHARGE_REQUEST_CODE ||requestCode == CHARGECARD_REQUEST_CODE)) {
            Run.excuteJsonTask(new JsonTask(), new LoadCheckoutHistoryTask(0));
            Run.excuteJsonTask(new JsonTask(), new GetAcountInfoTask());
            mAdapter.notifyDataSetChanged();
        }
    }

    public class MyBillAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return payInfos.size();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = getActivity().getLayoutInflater().inflate(R.layout.item_my_bill_adapter, null);
                holder = new ViewHolder();
                holder.img = (ImageView) convertView.findViewById(R.id.iv_head);
                holder.tvTitle = (TextView) convertView.findViewById(R.id.tv_goods_title);
                holder.tvMoney = (TextView) convertView.findViewById(R.id.tv_goods_money);
                holder.tvtime = (TextView) convertView.findViewById(R.id.tv_goods_time);
                holder.ivStatus = (ImageView) convertView.findViewById(R.id.iv_bill_statu);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            BillPayInfo info = payInfos.get(position);
            Log.i("info.getTime()", info.getTime());
//            String time = DateFormat.format("MM-dd", Long.parseLong(info.getTime())).toString();
            String time = Run.getCurrentNewFormatedCurrenTime(Long.parseLong(info.getTime()));

            holder.tvtime.setText(time);
//            holder.tvMoney.setText(info.getTime());
            holder.tvMoney.setText(info.getMoney());
            holder.tvTitle.setText(info.getTitle());

//			mImageLoader.showImage(holder.img, info.getImgPath());
            //&&isAdded()防止出现Fragment还没有Attach到Activity时调用getResource()产生异常
            if (TextUtils.equals("0", info.getStatus())&&isAdded()) {
                holder.ivStatus.setImageResource(R.drawable.me_item_outlay);
                holder.tvMoney.setTextColor(getActivity().getResources().getColor(R.color.fragment_top_bg));
            } else if (TextUtils.equals("1", info.getStatus())&&isAdded()) {
                holder.tvMoney.setTextColor(getActivity().getResources().getColor(R.color.result_points));
                holder.ivStatus.setImageResource(R.drawable.me_item_earning);
            } else if (TextUtils.equals("2", info.getStatus())&&isAdded()) {
                holder.tvMoney.setTextColor(getActivity().getResources().getColor(R.color.fragment_top_bg));
                holder.ivStatus.setImageResource(R.drawable.me_item_earning);
            } else if (TextUtils.equals("3", info.getStatus())&&isAdded()) {
                holder.ivStatus.setImageResource(R.drawable.me_item_outlay);
            }

            return convertView;
        }

        class ViewHolder {
            ImageView img;
            TextView tvTitle;
            TextView tvMoney;
            TextView tvtime;
            ImageView ivStatus;
        }

    }

    /**
     * 获取概要信息账户余额、总支出、总收入
     */
    private class GetAcountInfoTask implements JsonTaskHandler {

        @Override
        public void task_response(String json_str) {
            hideLoadingDialog_mt();
            try {
                JSONObject all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONObject data = all.getJSONObject("data");
                    String total = data.optString("total");
                    String anImport = data.optString("import");
                    String explode = data.optString("explode");
                    Double dImport = Double.parseDouble(anImport);
                    Double dExplode = Double.parseDouble(explode);
                    Double dTotal = Double.parseDouble(total);
                    DecimalFormat df = new DecimalFormat("0.00");
                    ((TextView) findViewById(R.id.account_balance_money))
                            .setText(df.format(dTotal));
                    ((TextView) findViewById(R.id.account_balance_import))
                            .setText(df.format(dImport));
                    ((TextView) findViewById(R.id.account_balance_explode))
                            .setText(df.format(dExplode));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public JsonRequestBean task_request() {
            if (!mListView.isRefreshing() && isFrist) {
                showCancelableLoadingDialog();
            }
            return new JsonRequestBean("mobileapi.deposits.get_info");
        }
    }

    /**
     * 获取预存流水
     */
    public class MyAccountDetailTask implements JsonTaskHandler {

        public MyAccountDetailTask() {
        }

        @Override
        public void task_response(String json_str) {
            accountLists.clear();
            hideLoadingDialog_mt();
            mListView.onRefreshComplete();

            JSONObject all = null;
            try {
                all = new JSONObject(json_str);
                JSONObject data = all.getJSONObject("data");
                JSONArray array=    data.getJSONArray("serial_list");

                currentTotal+=array.length();
                total=  data.optInt("count");
                //判断没有数据时候处理
                if (array != null && array.length() > 0) {
                    for (int i = 0; i < array.length(); i++) {
                        JSONObject obj = array.getJSONObject(i);
                        /*
                        * 	private String imgPath;
							private String title;
							private String status;//账单状态,0为进账单,1为出账单,2为佣金账单,3为待确认账单
							private String money;
							private String time;
							private int lastId;
						*
						* */
                        double import_money = obj.optDouble("import_money", 0.00);
                        double explode_money = obj.optDouble("explode_money", 0.00);
                        BillPayInfo info = new BillPayInfo();
                        if (import_money > 0) {
                            //进账单
                            info.setStatus("0");
                        } else if (explode_money > 0) {
                            //出账单
                            info.setStatus("1");
                        }
                        if (import_money > 0) {
                            info.setMoney(Run.buildString("+", new DecimalFormat("0.00").format(import_money)));
                        } else if (explode_money > 0) {
                            info.setMoney(Run.buildString("-", new DecimalFormat("0.00").format(explode_money)));
                        }
                        info.setTitle(obj.optString("message"));
                        info.setTime(obj.optString("mtime"));

                        payInfos.add(info);
                       // mAdapter.notifyDataSetChanged();

                    }
                    mAdapter.notifyDataSetChanged();
                } else {
//                    Toast.makeText(getActivity(), "没有更多新数据啦！", Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
            mTask = null;
        }


        @Override
        public JsonRequestBean task_request() {

            if (!mListView.isRefreshing() && isFrist) {
                showCancelableLoadingDialog();
            }
            JsonRequestBean req = new JsonRequestBean("mobileapi.deposits.get_serial_list");
            req.addParams("pageNo", String.valueOf(pageNo));
            req.addParams("pageSize", String.valueOf(pageSize));
            return req;
        }
    }

    //获取账单
    class MyPayDetailTask implements JsonTaskHandler {

        @Override
        public void task_response(String json_str) {
            try {
                hideLoadingDialog_mt();
                mListView.onRefreshComplete();
                JSONObject all = new JSONObject(json_str);
                if (Run.checkRequestJson(mActivity, all)) {
                    JSONArray array = all.getJSONObject("data").getJSONArray("advlogs");
                    for (int i = 0, n = array.length(); i < n; i++) {
                        JSONObject obj = array.getJSONObject(i);
                        double import_money = obj.optDouble("import_money", 0.00);
                        double explode_money = obj.optDouble("explode_money", 0.00);
                        String is_fx = obj.optString("is_fx");
                        String is_finish = obj.optString("is_finish");
                        BillPayInfo info = new BillPayInfo();
                        if (TextUtils.equals("true", is_finish) && TextUtils.equals("true", is_fx)) {
                            //为佣金账单
                            info.setStatus("2");
                        } else if (TextUtils.equals("false", is_finish) && TextUtils.equals("true", is_fx)) {
                            //待确认账单
                            info.setStatus("3");
                        } else if (import_money > 0) {
                            //进账单
                            info.setStatus("0");
                        } else if (explode_money > 0) {
                            //出账单
                            info.setStatus("1");
                        }
                        if (import_money > 0) {
                            info.setMoney(Run.buildString("+", import_money));
                        } else if (explode_money > 0) {
                            info.setMoney(Run.buildString("-", explode_money));
                        }
                        JSONObject goodsObject = obj.optJSONObject("goods");
                        info.setImgPath(obj.optString("image"));
                        if (goodsObject != null) {
                            info.setTitle(goodsObject.optString("name"));
                        } else {
                            info.setTitle(obj.optString("message"));
                        }
                        info.setTime(obj.optString("mtime"));
                        payInfos.add(info);
                    }
                }
                mAdapter.notifyDataSetChanged();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public JsonRequestBean task_request() {
            if (!mListView.isRefreshing() && isFrist) {
                showCancelableLoadingDialog();
            }
            JsonRequestBean req = new JsonRequestBean("mobileapi.member.get_payment_detail");
            req.addParams("pay_status", pay_status);
            req.addParams("page_no", String.valueOf(mPageNum));
            return req;
        }
    }


    private class BillPayInfo {
        private String imgPath;
        private String title;
        private String status;//账单状态,0为进账单,1为出账单,2为佣金账单,3为待确认账单
        private String money;
        private String time;
        private int lastId;
        private int color;

        public BillPayInfo() {
            super();
        }
//		public BillPayInfo(String imgPath, String title, String status,
//						   String money, String time) {
//			super();
//			this.imgPath = imgPath;
//			this.title = title;
//			this.status = status;
//			this.money = money;
//			this.time = time;
//		}

        public String getImgPath() {
            return imgPath;
        }

        public void setImgPath(String imgPath) {
            this.imgPath = imgPath;
        }

        public int getLastId() {
            return lastId;
        }

        public void setLastIde(int lastId) {
            this.lastId = lastId;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public int getColor() {
            return color;
        }

        public void setColor(int color) {
            this.color = color;
        }

        public String getStatus() {
            return status;
        }

        public void setStatus(String status) {
            this.status = status;
        }

        public String getMoney() {
            return money;
        }

        public void setMoney(String money) {
            this.money = money;
        }

        public String getTime() {
            return time;
        }

        public void setTime(String time) {
            this.time = time;
        }

        @Override
        public String toString() {
            return "BillPayInfo{" +
                    "imgPath='" + imgPath + '\'' +
                    ", title='" + title + '\'' +
                    ", status='" + status + '\'' +
                    ", money='" + money + '\'' +
                    ", time='" + time + '\'' +
                    ", lastId=" + lastId +
                    ", color=" + color +
                    '}';
        }
    }


}
